<template>
  <div ref="barCharts" :style="{ 'width': width, 'height': height }"></div>
</template>

<script>
import * as echarts from 'echarts';
import macarons from './macarons.json';
import { on, off } from "@/utils";

export default {
  name: 'BarChart',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    height: {
      type: String,
      default: '480px'
    },
    width: {
      type: String,
      default: '100%'
    },
    chartData: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      barCharts: null
    };
  },
  methods: {
    initChart() {
      this.barCharts = echarts.init(this.$refs.barCharts, 'macarons');
      this.setOption(this.chartData);
    },
    setOption({title, subTitle, legend, xAxis, series} = {}) {
      const option = {
        title: {
          text: title,
          x: 'center',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        legend: {
          data: legend,
          top: '30',
        },
        grid: {
          left: '0',
          right: '2%',
          bottom: '3%',
          top: '70',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data: xAxis,
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: series,
      };
      // 设置副标题
      if (subTitle && subTitle !== '') {
        option.title.subtext = subTitle;
        option.legend.top = '48';
        option.grid.top = '88';
      }
      this.barCharts.setOption(option);
    },
    resize() {
      this.barCharts.resize();
    },
    showLoading() {
      this.barCharts && this.barCharts.showLoading();
    },
    hideLoading() {
      this.barCharts && this.barCharts.hideLoading();
    }
  },
  watch: {
    chartData: {
      handler(val) {
        this.barCharts.clear();
        this.setOption(val);
      },
      deep: true
    },
    loading(val) {
      if (val) {
        this.showLoading();
      } else {
        this.hideLoading();
      }
    }
  },
  mounted() {
    echarts.registerTheme('macarons', macarons.theme);
    this.$nextTick(() => {
      this.initChart();
      on(window, 'resize', this.resize);
    });
  },
  beforeDestroy() {
    off(window, 'resize', this.resize);
    if (!this.barCharts) {
      return;
    }
    this.barCharts.dispose();
    this.barCharts = null;
  },
};
</script>

<style scoped>

</style>
